package com.example.service.util.service;

import com.example.common.redis.service.RedisService;
import com.example.common.util.enums.BusinessEnum;
import com.example.common.util.exception.BusinessException;
import com.example.service.util.utils.JwtUtils;
import com.example.common.util.utils.StringUtils;
import org.springframework.stereotype.Component;
import com.example.service.util.properties.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author juzipi
 * @Date 2021/7/17 10:44
 * @Info
 */
@Component
public class TokenService {


    @Resource
    private RedisService redisService;


    /**
     * 获取token
     * @param userId 用户id为key 以及jwt荷载
     * @param userName jwt荷载
     * @return
     */
    public String getToken(Long userId, String userName){
        String token = JwtUtils.createToken(userId, userName, UserPropertiesVariable.secret);
        //存入redis，key就是手机号(划掉),因为发送验证码时的key也是手机号，冲突了
        redisService.setCacheObject(Long.toString(userId),token,UserPropertiesVariable.expireTime, TimeUnit.MINUTES);
        return token;
    }


    /**
     * 删除token
     * @param phone
     * @return
     */
    public Boolean delToken(String phone){
        return redisService.deleteObject(phone);
    }


    /**
     * 获取用户id
     * @param request
     * @return
     */
    public Long getUserId(HttpServletRequest request) {
        String token = request.getHeader(UserPropertiesVariable.header);
        if (StringUtils.isNotEmpty(token)){
            return JwtUtils.getUserId(token);
        }
        throw new BusinessException(BusinessEnum.TOKEN_ERROR);
    }


    public Map<String,Object> getPayMap(Long orderId) {
        return redisService.getCacheObject(orderId.toString());
    }
}
